# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
import collections
import copy
import datetime
import fnmatch
import logging
import os
import re
import time
from dateutil.relativedelta import relativedelta
from operator import itemgetter

import json
import werkzeug
from lxml import etree
from lxml.etree import LxmlError
from lxml.builder import E

from odoo import api, fields, models, tools, SUPERUSER_ID, _
from odoo.exceptions import ValidationError
from odoo.http import request
from odoo.modules.module import get_resource_from_path, get_resource_path
from odoo.osv import orm
from odoo.tools import config, graph, ConstantMapping, SKIPPED_ELEMENT_TYPES
from odoo.tools.convert import _fix_multiple_roots
from odoo.tools.parse_version import parse_version
from odoo.tools.safe_eval import safe_eval
from odoo.tools.view_validation import valid_view
from odoo.tools.translate import encode, xml_translate, TRANSLATED_ATTRS
from xml.dom import minidom
import xml.etree.ElementTree as ET


class View(models.Model):
    _name = 'ir.ui.view'
    _inherit = ['ir.ui.view']
    doc=None
    order_line1 = fields.One2many('fhgroups.button', 'pam_isolation_id', string=u'子表', copy=True)
    order_line2 = fields.One2many('fhgroups.field', 'pam_isolation_id', string=u'子表', copy=True)
	

	
    @api.multi		
    def action_funproved0(self):
        self.test_load_xml()

        print('-------------------------')		
        return True

		
		
    @api.multi		
    def action_funproved2(self):
        self.Laction_funproved2()
        self.Laction_funproved2II()		
        return True
    @api.multi		
    def Laction_funproved2(self):
        #self.test_load_xml()
        objpath = self.env['fhgroups.tb_path'].search([])[0].moldepath		
        larch_base=self.arch_base
        larch_base2=""
        k=0	
        #更新groups权限内容
        tree = ET.parse(objpath+'/user.xml')
        root = tree.getroot() 
		
        for s in self.order_line1:
            print('-------s.name------------------')

            print(s.name)
            g=0
            for node in root.iter('button'):
                if(k==g):
                    if(s.groups_xml_id!=""):			
                        node.set('groups', s.groups_xml_id)
                g=g+1
            k=k+1				
		
			#ET.dump(new_xml)
        #保存XML修改结果			
        tree.write(objpath+"/user2.xml",'utf-8')				
			
			
        print('----------ok---------------')
        #读取结果到试图中
        fo=open(objpath+"/user2.xml","rb")
        lineST='<?xml version="1.0"?>\n'
        for line in fo.readlines(): 
            lineST=lineST+str(line.decode('utf-8'))+""
        print('---------7777777777777----------------')
        print(lineST)		
        values={}
        values["arch_base"]=lineST
        print('----------lineST------------')		
        print(lineST)
        super(View, self).write(values)	
        return True
    @api.multi		
    def Laction_funproved2II(self):
        objpath = self.env['fhgroups.tb_path'].search([])[0].moldepath		
        larch_base=self.arch_base
        larch_base2=""
        k=0	
        j=-1			
        #更新groups权限内容
        tree = ET.parse(objpath+'/user2.xml')
        root = tree.getroot() 
		
        for s in self.order_line2:
            s_name=s.name
            _ifnolabel_nodes=s._ifnolabel_nodes		

            g=0
            for node in root.iter('field'):
                if(k==g):
				
                    if(s.groups_xml_id!=""):					
                        node.set('groups', s.groups_xml_id)									
                g=g+1

                print(node)					
                print('----------g=g+1----------------')						

            k=k+1

        #保存XML修改结果			
        tree.write(objpath+"/user3.xml",'utf-8')				
			
			
        print('----------ok---------------')
        #读取结果到试图中
        fo=open(objpath+"/user3.xml","rb")
        lineST='<?xml version="1.0"?>\n'
        for line in fo.readlines(): 
            lineST=lineST+str(line.decode('utf-8'))+""
        print('---------7777777777777----------------')
        print(lineST)		
        values={}
        values["arch_base"]=lineST
		
        super(View, self).write(values)	
        return True 	
    def get_attrvalue(self,node, attrname):
         return node.getAttribute(attrname) if node else ''

    def get_nodevalue(self,node, index = 0):
        return node.childNodes[index].nodeValue if node else ''

    def get_xmlnode(self,node, name):
        return node.getElementsByTagName(name) if node else []



    def test_load_xml(self):
        objpath = self.env['fhgroups.tb_path'].search([])[0].moldepath	
        print(objpath) 	

        document = open(objpath+"/user.xml", "wb+") 
        document.write(self.arch_base.encode(encoding='UTF-8'))

        document.close()
		
		
        #提取按钮节点	
        user_list = self.get_xml_data(objpath+"/user.xml")

	
    def get_xml_data(self,filename = 'user.xml'):
	
	
	
        doc = minidom.parse(filename) 
        root = doc.documentElement

        user_nodes = self.get_xmlnode(root, 'header')
       
        obj = self.env['fhgroups.button']	
        
        idx0=0
        for node in user_nodes: 

            _nodes2=node.getElementsByTagName('button')
            _nodes2text=""	
            for  _node in _nodes2:
                attrs = _node.attributes;	
                idx=0
			
                while(attrs.length>idx):
                    at_item=attrs.item(idx)		
                    print(at_item.nodeName+'="'+at_item.nodeValue+'"')
                    _nodes2text=_nodes2text	+" "+at_item.nodeName+'="'+at_item.nodeValue+'"'			
                    idx=idx+1
                print('-----------_nodes2text-----------------')
                print(_node)    			
                print(_nodes2text)
                vals={}
                vals["name"]="<button "+_nodes2text+" />"
                vals["pam_isolation_id"]=self.id			
                obj.create(vals)								
                _nodes2text=""		
        return True	
	
	
    @api.multi		
    def action_toprovekk(self):
        self.test_load_xmlfield()

        print('-------------------------')		
        return True	
    @api.multi		
    def action_toprovekk002(self):
        self.test_load_xmlfield_tree()

        print('-------------------------')		
        return True
		
		
    def test_load_xmlfield(self):
        objpath = self.env['fhgroups.tb_path'].search([])[0].moldepath	
        print(objpath) 	

        document = open(objpath+"/user.xml", "wb+") 
        document.write(self.arch_base.encode(encoding='UTF-8'))

        document.close()
		
		
        #提取按钮节点	
        self.get_xml_datafield(objpath+"/user.xml")
        #self.get_xml_datafield_tree(objpath+"/user.xml")		
    def test_load_xmlfield_tree(self):
        objpath = self.env['fhgroups.tb_path'].search([])[0].moldepath	
        print(objpath) 	

        document = open(objpath+"/user.xml", "wb+") 
        document.write(self.arch_base.encode(encoding='UTF-8'))

        document.close()
		
		
        #提取按钮节点	
        #self.get_xml_datafield(objpath+"/user.xml")
        self.get_xml_datafield_tree(objpath+"/user.xml")
        #self.get_xml_datafield_tree_button(objpath+"/user.xml")
	
    def get_xml_datafield(self,filename = 'user.xml'):
	
	
	
        doc = minidom.parse(filename) 
        root = doc.documentElement

		
        user_nodes = self.get_xmlnode(root, 'header')
       
        obj = self.env['fhgroups.field']	
        
        idx0=0
        for node in user_nodes: 

            _nodes2=node.getElementsByTagName('field') 		
            _nodes2text=""

		
            for  _node in _nodes2:
			
                _ifnolabel_nodes="False"			
                attrs = _node.attributes;	
                idx=0
			
                while(attrs.length>idx):
                    at_item=attrs.item(idx)		
                    print(at_item.nodeName+'="'+at_item.nodeValue+'"')
                    if(at_item.nodeName=="nolabel"):
                        _ifnolabel_nodes="True"					
					
                    _nodes2text=_nodes2text	+" "+at_item.nodeName+'="'+at_item.nodeValue+'"'	
    				#_nodes2text=_nodes2text	+at_item.nodeText	
					
    				#print('-------------------------------------')			
                    idx=idx+1
                print('-----------_nodes2text-----------------')
                print(_node)    			
                print(_nodes2text)
                vals={}
                vals["name"]="<field "+_nodes2text+" />"
                vals["pam_isolation_id"]=self.id
                vals["_ifnolabel_nodes"]=_ifnolabel_nodes				
                #if(_ifnolabel_nodes==False):               				
                obj.create(vals)
					
                _nodes2text=""		
		
		
		
		
		
		
		
        user_nodes = self.get_xmlnode(root, 'sheet')
       
        obj = self.env['fhgroups.field']	
        
        idx0=0
        for node in user_nodes: 

            _nodes2=node.getElementsByTagName('field') 		
            _nodes2text=""

		
            for  _node in _nodes2:
			
                _ifnolabel_nodes="False"			
                attrs = _node.attributes;	
                idx=0
			
                while(attrs.length>idx):
                    at_item=attrs.item(idx)		
                    print(at_item.nodeName+'="'+at_item.nodeValue+'"')
                    if(at_item.nodeName=="nolabel"):
                        _ifnolabel_nodes="True"					
					
                    _nodes2text=_nodes2text	+" "+at_item.nodeName+'="'+at_item.nodeValue+'"'	
    				#_nodes2text=_nodes2text	+at_item.nodeText	
					
    				#print('-------------------------------------')			
                    idx=idx+1
                print('-----------_nodes2text-----------------')
                print(_node)    			
                print(_nodes2text)
                vals={}
                vals["name"]="<field "+_nodes2text+" />"
                vals["pam_isolation_id"]=self.id
                vals["_ifnolabel_nodes"]=_ifnolabel_nodes				
    			#if(_ifnolabel_nodes==False):               				
                obj.create(vals)
					
                _nodes2text=""




				
        return True


    def get_xml_datafield_tree(self,filename = 'user.xml'):	
        doc = minidom.parse(filename) 
        root = doc.documentElement

        user_nodes = self.get_xmlnode(root,'field')
       
        obj = self.env['fhgroups.field']	
        
 
		
        _nodes2text=""			
		
        for node in user_nodes:

            idx=0		
            attrs = node.attributes			
            while(attrs.length>idx):
                at_item=attrs.item(idx)		
                print(at_item.nodeName+'="'+at_item.nodeValue+'"')
                _nodes2text=_nodes2text	+" "+at_item.nodeName+'="'+at_item.nodeValue+'"'					
                idx=idx+1			
            vals={}
            vals["name"]="<field "+_nodes2text+" />"
            vals["pam_isolation_id"]=self.id			
            obj.create(vals)								
            _nodes2text=""										
        return True			
		
    def get_xml_datafield_tree_button(self,filename = 'user.xml'):	
        doc = minidom.parse(filename) 
        root = doc.documentElement

        user_nodes = self.get_xmlnode(root, 'tree')
       
        obj = self.env['fhgroups.button']	
        
        idx=0
		
        _nodes2text=""			
		
        for node in user_nodes: 

            attrs = node.attributes			
            while(attrs.length>idx):
                at_item=attrs.item(idx)		
                print(at_item.nodeName+'="'+at_item.nodeValue+'"')
                _nodes2text=_nodes2text	+" "+at_item.nodeName+'="'+at_item.nodeValue+'"'					
                idx=idx+1			
            vals={}
            vals["name"]="<button "+_nodes2text+" />"
            vals["pam_isolation_id"]=self.id			
            obj.create(vals)								
            _nodes2text=""										
        return True		
		
		
class fhgroups_button(models.Model):
    _name = 'fhgroups.button'
    _description = u''
    @api.depends('pam_groups_id')	
    def _amount_all(self):
        groups_xml_id =""
        print('-------------------触发器----------------------')			
        obj = self.env['ir.model.data']		
        for order in self:
			

            obj = obj.search([('res_id','=',order.pam_groups_id.id),('model','=','res.groups')])
            order.update({'groups_xml_id':str(obj.module)+'.'+str(obj.name),})			
            if(obj.module==False or obj.name==False):	
                order.update({'groups_xml_id':"",})		
        return True	
	
    pam_isolation_id=fields.Many2one('ir.ui.view',u'主表',readonly=False,required=False,translate=False)
    name = fields.Char(string=u'button')
    groups_xml_id = fields.Char(compute='_amount_all',string=u'groups_xml_id')
    pam_groups_id=fields.Many2one('res.groups',u'权限组',readonly=False,required=False,translate=False)	
	
	
class fhgroups_field(models.Model):
    _name = 'fhgroups.field'
    _description = u''
    _order = 'id'	
    @api.depends('pam_groups_id')	
    def _amount_all(self):
        groups_xml_id =""
        print('-------------------触发器----------------------')			
        obj = self.env['ir.model.data']		
        for order in self:
			

            obj = obj.search([('res_id','=',order.pam_groups_id.id),('model','=','res.groups')])
            order.update({'groups_xml_id':str(obj.module)+'.'+str(obj.name),})			
            if(obj.module==False or obj.name==False):	
                order.update({'groups_xml_id':"",})		
        return True	
	
    pam_isolation_id=fields.Many2one('ir.ui.view',u'主表',readonly=False,required=False,translate=False)
    name = fields.Char(string=u'button')
    _ifnolabel_nodes = fields.Char(string=u'ifnolabel')	
    groups_xml_id = fields.Char(compute='_amount_all',string=u'groups_xml_id')
    pam_groups_id=fields.Many2one('res.groups',u'权限组',readonly=False,required=False,translate=False)	
	
	
	